import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.ColorModel;
import java.awt.image.DirectColorModel;
import java.awt.image.ImageConsumer;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;

final class GraphicsBuffer implements ImageProducer, ImageObserver {
	private final ColorModel componentColorModel;
	private final Image image;
	private ImageConsumer imageConsumer;
	private final int canvasHeight;
	private final int canvasWidth;
	public final int[] componentPixels;

	public synchronized void addConsumer(ImageConsumer imageConsumer) {
		this.imageConsumer = imageConsumer;
		imageConsumer.setDimensions(canvasWidth, canvasHeight);
		imageConsumer.setProperties(null);
		imageConsumer.setColorModel(componentColorModel);
		imageConsumer.setHints(14);
	}

	public void drawGraphics(Graphics g, int x, int y) {
		setPixels();
		g.drawImage(image, x, y, this);
	}

	public boolean imageUpdate(Image image, int i, int j, int k, int l, int i1) {
		return true;
	}

	public void init() {
		Renderer2D.init(canvasWidth, canvasHeight, componentPixels);
	}

	public synchronized boolean isConsumer(ImageConsumer imageconsumer) {
		return imageConsumer == imageconsumer;
	}

	private synchronized void setPixels() {
		if (imageConsumer != null) {
			imageConsumer.setPixels(0, 0, canvasWidth, canvasHeight, componentColorModel,
			componentPixels, 0, canvasWidth);
			imageConsumer.imageComplete(2);
		}
	}

	public synchronized void removeConsumer(ImageConsumer imageconsumer) {
		if (imageConsumer == imageconsumer) {
			imageConsumer = null;
		}
	}

	public void requestTopDownLeftRightResend(ImageConsumer imageconsumer) {
		System.out.println("TDLR");
	}

	public void startProduction(ImageConsumer imageconsumer) {
		addConsumer(imageconsumer);
	}

	public GraphicsBuffer(int width, int height, Component component) {
		canvasWidth = width;
		canvasHeight = height;
		componentPixels = new int[width * height];
		componentColorModel = new DirectColorModel(32, 0xff0000, 65280, 255);
		image = component.createImage(this);
		setPixels();
		component.prepareImage(image, this);
		setPixels();
		component.prepareImage(image, this);
		setPixels();
		component.prepareImage(image, this);
		init();
	}
}
